<template>
	<m-layout class="order-details" title="确认订单" gap="24 24 186 24" :goHome="true">
		<template v-if="sendTotal">
			<m-address></m-address>
		</template>
		<template v-for="item in goodList">
			<orderCard className="orderCard" :key="item.id" :specification="item.unitName" :item="item"
				@onChange="addCard"></orderCard>
		</template>


		<m-block>

			<m-cell lIcon="icon-youhuiquan1" lIconColor="#FF6D6D" lIconSize="45" title="使用代金券"
				@click="Jump('/pagesA/coupon/coupon?type=pay')">
				<m-text slot="right" v-if="couponid">已选：1张</m-text>
				<!-- {{card_token}} -->
			</m-cell>

		</m-block>

		<m-block className='goods-msg' gap="30 20 0" spa="20 0 0 0">
			<view class="cell  flex-between" v-if="totalPrice['sPrice']>0">
				<text>商品总价(共{{totalPrice['amount']}}件商品）</text>
				<view class="right">
					<m-number :cny="paytype  == 1 " unit="积分" :value="totalPrice['sPrice']" weight="600" />
				</view>
			</view>
			<template v-if="totalPrice['freight']">
				<view class="cell  flex-between">
					<text>配送方式</text>
					<view class="right">
						<text>快递运输</text>
					</view>
				</view>
				<view class="cell flex-between">
					<text>运费</text>
					<view class="right">
						<template v-if="paytype == 1">
							<m-number leftText="￥" :value="totalPrice['freight']" weight="600" />
						</template>
						<template v-else>
							<m-number unit="积分" :value="totalPrice['freight']" weight="600" />
						</template>
					</view>
				</view>
			</template>
			<view class="cell  flex-between" v-if="couponid && !isCard">
				<text>代金券金额</text>
				<view class="right">
					<!-- <text v-if="sendTotal">含运费</text> -->
					<m-number cny :value="couponInfo['amt']" weight="600" color="#FA2B47" />
				</view>
			</view>
			<view class="cell  flex-between" v-if="totalPrice['tPrice'] > 0">
				<text>需付款</text>
				<view class="right">
					<!-- <text v-if="sendTotal">含运费</text> -->
					<m-number :cny="paytype  == 1 " unit="积分" :value="totalPrice['tPrice']" weight="600"
						color="#FA2B47" />
				</view>
			</view>
			<!-- <template v-if="isEmpty(toatalJf)">
				<view class="cell  ">
					<m-text display="block">需消耗</m-text>
					<m-block className="list-box" gap="24 24 0" spa="25 0 0 " bgColor="#F6F6F6">
						<template v-for="(item2,idx) in toatalJf">
							<view :key="idx" class="flex-between" style="padding-bottom: 24rpx;">
								<m-text color="#999" ftsize="26" :text="Coin[idx]"></m-text>
								<m-text color="#999" ftsize="26" :text="item2"></m-text>
							</view>
						</template>
					</m-block>
				</view>
			</template> -->

		</m-block>
		<m-block gap="24" spa="20 0" title="下单备注 [选填]">
			<view class="from-item">
				<textarea v-model="remark" :maxlength="100" auto-height placeholder-class="placeholder"
					placeholder="请输入备注信息" />
			</view>
		</m-block>

		<!-- 	<m-block class='service flex-center' gap="30 20" spa="20 0"
			@click="Jump('/pages/dialogue/dialogue?touserid='+ goodList[0].sellerUserID + '&touserName=' + goodList[0].sellerUserName)">
			<m-icon size="42" spa="0 16 0 0" type="icon-xiaoxikefu" />
			<text>联系客服</text>
		</m-block> -->
		<!-- <icp></icp> -->
		<view class="footer ">
			<!-- <view>
				<view class="totals flex">
					<template v-if="totalPrice['tPrice']>0">
						<m-number leftText="￥" :value="totalPrice['tPrice']" weight="600" color="#FA2B47"></m-number>
					</template>
				</view>
				<view class="total_txt">共支付</view>
			</view> -->
			<template v-if="unsalable">
				<m-button block @click="goPay">提交订单</m-button>
			</template>
			<template v-else>
				<m-button block type="disabled">暂不可售</m-button>
			</template>
		</view>

		<uni-popup ref="copyShow" type="center">
			<view class="copy-popup flex-column">
				<view class="center flex-center"><text>请确认支付是否已完成</text></view>
				<view class="btn-box flex-between" @click="$refs.copyShow.close()">
					<text @click="payShow = true">继续支付</text>
					<text @click="Jump({url: '/pagesA/order/order',mode: 2})">已完成支付</text>
				</view>
			</view>
		</uni-popup>
	</m-layout>
</template>

<script>
	import { CreateOrder } from '@/api/Order.js'
	import { ShopCar_Edit } from '@/api/Goods.js'
	import { isEmpty } from '@/libs/fn/verify.js'
	import { mapState } from 'vuex'
	export default {
		data() {
			return {
				couponid: "",
				remark: "",
				isCard: 0, //是否购物车支付  默认0 否
				payShow: false,
				payLoading: false,

				isMore: false,
				paySumAmount: 0, // 支付总价格
				orderNoList: [], // 商品订单号集合
				freight: 0,
				unsalable: true, //商品是否可售
			};
		},
		computed: {
			...mapState({
				nowId: state => state.address.nowId,
				addressObj: state => state.address.addressObj,
				coinConfig: state => state.general.coinConfig,
				config: state => state.general.config,
				enum: state => state.general.enum,
				goodList: state => state.goods.payGoodsList,
				userbalance: state => state.user.userbalance,
				userinfo: state => state.user.userinfo,
				coupon: state => state.user.coupon,
			}),
			Coin() {
				return this.enum['Coin']
			},

			//计算总价  , 总量 ,总债权积分 
			totalPrice() {
				let amount = 0,
					fee = 0,
					fee2 = 0,
					tPrice = 0,
					sPrice = 0;

				//当前选择的are地址
				this.goodList.forEach(item => {
					sPrice += this.times(item.price, item.buycount);
					tPrice += this.times(item.price, item.buycount);

					//-------------------------叠加运费计算---------------------
					///计算运费
					// //获取当前偏远地区列表
					// const extfee = item['extfee']
					// //输出位地址集合
					// const extfeeAddr = extfee.map(item => {
					// 	return item.addr
					// }, [])
					//筛选出当前选择地址 是否符合商品设置的偏远地址 (下标)
					// let index = '';
					// try {
					// 	const addressN = this.addressObj[this.nowId]['are']
					// 	index = extfeeAddr.findIndex(item => addressN.includes(item));
					// } catch (e) {
					// 	//TODO handle the exception
					// }
					// if (index != -1) {
					// 	try {
					// 		//得到当前匹配的偏远地区运费
					// 		const ReFee = item['extfee'][index]['fee'] || 0
					// 		fee2 = ReFee
					// 	} catch (e) {
					// 		//TODO handle the exception
					// 	}
					// } else {
					// 	fee2 = item.yf
					// }

					//------------------------- 结束 ---------------------
					fee2 = item.yf || 0
					//运费叠加计算
					if (item.dualyf != "0") {
						//叠加运费 
						item.fee2 = this.times(fee2, item.buycount)
						fee = this.plus(fee, this.times(fee2, item.buycount));
					} else {
						fee = this.plus(fee, fee2);
						item.fee2 = fee2
					}
					amount += item.buycount;
				})
				return {
					amount: amount, //总数
					freight: fee, //运费
					tPrice: this.minus(tPrice, this.couponInfo['amt']), //总需
					sPrice: sPrice, //原价
				}
			},
			leftText() {
				return this.totalPrice['sPrice'] > 0 ? '￥' : ''
			},
			sendTotal() {
				// //；列表有一个需要填写收货地址，默认显示收货地址
				// let idx = this.goodList.findIndex(item => {
				// 	return item['sendTotal'] == 1
				// })
				// console.log("idx",idx)
				// return idx != -1
				return true
			},
			couponInfo() {
				if (!this.couponid) {
					return {
						amt: 0
					}
				}

				try {
					let item = this.coupon[this.couponid]
					return item
				} catch {
					return {
						amt: 0
					}
				}
			},
			// toatalJf() {
			// 	try {
			// 		let jf = {};
			// 		for (let var1 in this.Coin) { jf[var1] = 0 }
			// 		this.goodList.forEach(item => {
			// 			let name = item['feecoinid'];
			// 			const jfNum = jf[name] || 0
			// 			jf[name] = this.plus(jfNum, this.times(item.buycount, item.feejf))
			// 		})

			// 		if(this.isWards == 1){
			// 			jf[1] = this.plus(jf[1], this.totalPrice['freight'])
			// 		}else{
			// 			jf[2] = this.plus(jf[2], this.totalPrice['freight'])
			// 		}

			// 		let filterTotal = {}
			// 		for (let var2 in jf) {
			// 			if (jf[var2] > 0) {
			// 				filterTotal[var2] = jf[var2]
			// 			}
			// 		}
			// 		return filterTotal
			// 	} catch (e) {
			// 		console.log(e)
			// 		return 0
			// 		//TODO handle the exception
			// 	}
			// },
			paytype() {
				return this.goodList[0]['coinid']
			},
			isWards() {
				return this.goodList[0]['wards']
			},
		},
		mounted() {},
		onLoad({ isCard }) {
			console.log(this.goodList)
			this.isCard = isCard || 0;
		},
		onShow() {

			console.log(this.coupon)
			console.log(this.coupon[this.couponid])
			// this.beforCreateOrder()
			//当重新显示页面时   关闭支付弹窗 打开确认付款弹窗
			if (this.payShow == true) {
				this.payShow = false;
				this.$refs.copyShow.open()
			}
		},
		methods: {
			isEmpty(i) {
				return !isEmpty(i)
			},
			//添加购物车数量
			async addCard(item) {
				let idx = this.goodList.findIndex((obs) => {
					return obs['id'] == item['id']
				})
				const arr = [...this.goodList]
				arr[idx] = { ...item }
				this.$store.commit('goods/SET_PAYGOODS', arr)
				if (!this.isCard) return
				let data = {
					carid: item.id,
					count: item.buycount,
				};
				const res = await ShopCar_Edit(data);
				if (!res.success) {
					this.Toast(res.msg)
					item.count = item.count - 1;
				}
			},

			//购买前验证
			async goPay() {
				if (!this.nowId) {
					return this.Toast('请选择收货地址')
				}
				// 创建商品订单   提交 
				if (this.isCard) {
					this.CreateOrder_Car();
				} else {
					this.seveOrder();
				}
			},
			// 创建商品订单   提交 
			async seveOrder() {
				let attrid = 0;
				const firstGoods = this.goodList[0]
				let onceParams = {
					gid: firstGoods['gid'],
					unitid: firstGoods['unitid'],
					buyCount: firstGoods['buycount'],
					headsUserId: firstGoods['headsUserId'],
					remark: this.remark,
				}
				if (this.couponid) {
					onceParams['couponid'] = this.couponid
				}
				const { success, data, msg } = await CreateOrder({
					goods: [onceParams],
					addrId: this.nowId,
					fromShopCard: 2
				})
				this.Toast(msg)
				if (success) {
					await this.sleep(1000)
					this.Jump({
						url: '/pages/shopping/surePay/surePay?ordercode=' + data,
						mode: 2
					})
				}
			},
			//购物车创建订单
			async CreateOrder_Car() {
				const carIDArr = this.goodList.map(item => {
					return {
						gid: item['gid'],
						unitid: item['unitid'],
						buyCount: item['buycount'],
						headsUserId: item['headsUserId'],
						remark: this.remark,
						// couponid: this.couponid,
					}
				}, [])
				const { success, data, msg } = await CreateOrder({
					goods: carIDArr,
					addrId: this.nowId,
					fromShopCard: 1
				})
				this.Toast(msg)
				if (success) {
					await this.sleep(1000)
					this.Jump({
						url: '/pages/shopping/surePay/surePay?orderid=' + data,
						mode: 1
					})
				}
			},

		},
	}
</script>

<style lang="scss">
	.orderCard {
		.order-card {
			margin-top: 0 !important;
		}

	}

	.order-details {
		background-size: 100% 326rpx;

		.status-box {
			margin-top: -20rpx;

			.status {
				text {
					padding-left: 18rpx;
					font-size: 36rpx;
					font-family: PingFang SC-Bold, PingFang SC;
					font-weight: bold;
					color: #FFFFFF;
				}
			}

			.hint {
				padding-top: 20rpx;
				text-align: center;
				font-size: 24rpx;
				font-family: PingFang SC-Regular, PingFang SC;
				font-weight: 400;
				color: #FFFFFF;

				.sy {
					padding-left: 20rpx;
				}
			}
		}

		.goods-msg {
			.title {
				text {
					font-size: 30rpx;
					font-family: PingFang SC-Bold, PingFang SC;
					font-weight: bold;
					color: #333;
				}
			}

			.cell {
				padding-bottom: 30rpx;

				&>text {
					font-size: 28rpx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #333;
				}

				.right {
					max-width: 60%;
					font-size: 28rpx;
					font-family: PingFang SC;
					font-weight: 400;
					color: #999999;
					text-align: right;

					.copy {
						padding-left: 20rpx;
						font-size: 30rpx;
						font-family: PingFang SC-Regular, PingFang SC;
						font-weight: 400;
						color: #333333;
					}

				}

				.debt-hint {}

				.debt {
					font-family: PingFang SC-Bold, PingFang SC;
					font-weight: bold;
					color: #333333;

					text:nth-of-type(1) {
						font-size: 40rpx;
					}

					text:nth-of-type(2) {
						font-size: 24rpx;
					}
				}

				.list-box {
					overflow: unset;

					&::after {
						content: '';
						display: block;
						width: 20rpx;
						height: 20rpx;
						background: #f6f6f6;
						position: absolute;
						top: -10rpx;
						left: 35rpx;
						transform: rotate(45deg);

					}
				}

			}

			.cell1 {
				border-top: 1rpx solid #EEEEEE;
				padding-top: 27rpx;
			}

			.more {
				border-top: 1px solid #EEEEEE;
				text-align: center;
				padding: 23rpx 0;
				font-size: 28rpx;
				font-family: Source Han Sans CN-Regular, Source Han Sans CN;
				font-weight: 400;
				color: #999999;
			}
		}

		.service {
			text {
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 400;
				color: #333333;
			}
		}


	}

	.from-item {
		textarea {
			box-sizing: border-box;
			margin-top: 20rpx;

			padding: 24rpx;
			width: 100%;
			background: #F6F6F6;
			border-radius: 10rpx;

			font-size: 26rpx;
		}

		.placeholder {
			font-size: 26rpx;
			font-family: PingFang SC-Regular, PingFang SC;
			font-weight: 400;
			color: #999999;
		}
	}

	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		z-index: 9;

		padding: 17rpx 24rpx;
		background: #FFFFFF;
		box-sizing: border-box;

		text-align: right;

		.totals {
			.p2 {
				font-size: 30rpx;
				font-family: PingFang SC;
				font-weight: 500;

				color: #FA2F43;

				.jia {
					padding: 0 10rpx;
				}
			}
		}

		.total_txt {
			font-size: 24rpx;
			font-family: Source Han Sans CN-Regular, Source Han Sans CN;
			font-weight: 400;
			color: #999999;
			text-align: start;
		}


	}


	.copy-popup {
		width: 582rpx;
		height: 264rpx;
		background: #ffffff;
		border-radius: 20rpx;

		.center {
			flex: 1;
			font-size: 32rpx;
			font-family: PingFang SC;
			font-weight: bold;
			color: #333333;
		}

		.btn-box {
			border-top: 1rpx solid #eeeeee;

			text {
				display: inline-block;
				flex: 1;
				text-align: center;
				padding: 26rpx 0;
				font-size: 26rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #666666;
			}

			text:nth-of-type(2) {
				border-left: 1rpx solid #eeeeee;
				color: #FF2323;
			}
		}
	}
</style>